﻿using HotChocolate.Language;
using HotChocolate.Utilities.Introspection;

namespace Gateway.Api.Infrastructures;

public sealed class Microservices
{
    private Microservices(MicroserviceSubgraph products, MicroserviceSubgraph orders)
    {
        Products = products;
        Orders = orders;
    }

    public MicroserviceSubgraph Products { get; }
    public MicroserviceSubgraph Orders { get; }

    public static async Task<Microservices> CreateAsync(CancellationToken ct = default)
    {
        var orders = new Uri("http://localhost:5020/graphql");
        var orderSchema = await DownloadSchemaAsync(orders, ct);

        var products = new Uri("http://localhost:5030/graphql");
        var productSchema = await DownloadSchemaAsync(products, ct);

        return new Microservices(
            new MicroserviceSubgraph("Orders", orders, orderSchema),
            new MicroserviceSubgraph("Products", products, productSchema));
    }

    private static async Task<DocumentNode> DownloadSchemaAsync(
        Uri uri,
        CancellationToken ct = default)
    {
        using var client = new HttpClient();
        client.BaseAddress = uri;
        return await IntrospectionClient.IntrospectServerAsync(client, ct);
    }
}